﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using DevExpress.Web.ASPxUploadControl;
using DevExpress.Web.Mvc;
using System.Data;
using System.IO;
using System.Reflection;
using System.Collections;
using DevExpress.Web.ASPxEditors;

namespace EnterpriseFund.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]  
    public class YGZAllowanceController : AdminBaseController
    {
        #region install

        public decimal Year{
            get{
                return Convert.ToDecimal(OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR));
            }
        }

        private string _strYearWhere;
        private BLL.YGZAllowance _bll = new BLL.YGZAllowance();

        public YGZAllowanceController()
        {
            _strYearWhere = "FYear=" + Year;
        }

        #endregion

        [AuthorityActionFilter("m_YGZAllowanceManager", Order = 1)]
        [LogPageActionFilter("营改增补助管理", Order = 2)]
        public ActionResult Index()
        {
            var ygzData = _bll.GetTable(_strYearWhere);
            return View(ygzData);
        }

        public ActionResult YGZAllowancePartial()
        {
            var ygzData = _bll.GetTable(_strYearWhere);
            return PartialView(ygzData);
        }

        //保存
        public string Save(Model.YGZAllowance model)
        {
            var msg = "";

            model.FUpdDate = DateTime.Now;
            model.FUpdEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            model.FUpdDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            model.FUpdIP = Request.UserHostAddress;

            if (string.IsNullOrEmpty(model.FYGZAllowanceNo))
            {
                model.FYGZAllowanceNo = DateTime.Now.ToString("yyyyMMddHHmmss") + "1";
                model.FEntityNo = GlobalConstant.ENTITYNO;
                model.FInsDate = model.FUpdDate;
                model.FInsEmpNo = model.FUpdEmplNo;
                model.FInsDeptNo = model.FUpdDeptNo;
                model.FInsIP = model.FUpdIP;

                if (_bll.Exists(model.FYear, model.NSRDZDAH, model.FPeriod))
                {
                    msg = "添加失败，该数据已存在！";
                    return msg;
                }

                msg = _bll.Add(model) ? "ok" : "err";
            }
            else
            {
                msg = _bll.Update(model) ? "ok" : "err";
            }

            return msg;
        }

        //编辑
        public ActionResult YGZAllowanceEdit(string id)
        {
            var model = new Model.YGZAllowance(Year);
            ViewBag.nsr = new Model.DJ_NSRXX();

            if(!string.IsNullOrEmpty(id))
            {
                model = _bll.GetModel(id);
                var nsr = new BLL.DJ_NSRXX().GetModel(model.NSRDZDAH, Year.ToString());
                ViewBag.nsr = nsr;
            }
            return View(model);
        }

        //删除
        public bool Delete(string id)
        {
            return _bll.Delete(id);
        }

        //导入
        public ActionResult YGZAllowanceImport()
        {
            if (Request["year"] == null)
            {
                return View();
            }
            else
            {
                var msg = SaveYGZExcel();
                ViewBag.Msg = msg;
                return View();
            }
        }

        //保存导入数据
        public string SaveYGZExcel()
        {
            var ErrMsg = "";


            var year = decimal.Parse(Request["year"]);
            var period = int.Parse(Request["period"]);
            var isDel = Request["isDelData"] == "C";


            //上传
            var uploadFiles = UploadControlExtension.GetUploadedFiles("upload");
            if (null == uploadFiles || uploadFiles.Length == 0)
            {
                ErrMsg = "请选择Excel文件！";
                return ErrMsg;
            }
            var upload = uploadFiles[0];
            var clintFileName = upload.FileName;
            var extName = clintFileName.Substring(clintFileName.LastIndexOf('.') + 1);
            var svrFileName = string.Format("{0}.{1}", DateTime.Now.ToString("yyyyMMddHHmm"), extName);
            var uploadoffiepath = string.Format("~/Publish/{0}/YGZ/{1}{2}/", GlobalConstant.ENTITYNO, DateTime.Now.Year, DateTime.Now.Month);
            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
            {
                Directory.CreateDirectory(uploadoffiepath);
            }
            upload.SaveAs(uploadoffiepath + svrFileName);

            //读取
            var dt = new BLL.SB_ZSXX().ReadExcelTitle(uploadoffiepath + svrFileName).Tables[0];

            //验证
            var cols = new List<string> { "年度", "期号", "纳税人编码", "纳税人名称", "补助金额" };
            foreach (var col in cols)
            {
                if (!dt.Columns.Contains(col))
                {
                    ErrMsg = "Excel文件格式错误！";
                    return ErrMsg;
                }
            }

            var models = new List<Model.YGZAllowance>();
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                var r = dt.Rows[i];
                var excelRowIndex = i + 2;

                if (year.ToString() != r["年度"].ToString())
                {
                    ErrMsg = "Excel文件第" + excelRowIndex + "行，年份数据有误！";
                    return ErrMsg;
                }

                if (period.ToString() != r["期号"].ToString())
                {
                    ErrMsg = "Excel文件第" + excelRowIndex + "行，期号数据有误！";
                    return ErrMsg;
                }

                if (r.IsNull("纳税人编码") || string.IsNullOrEmpty(r["纳税人编码"].ToString()))
                {
                    ErrMsg = "Excel文件第" + excelRowIndex + "行，纳税人编码不能为空！";
                    return ErrMsg;
                }

                var amount = 0m;
                if (!decimal.TryParse(r["补助金额"].ToString(), out amount))
                {
                    ErrMsg = "Excel文件第" + excelRowIndex + "行，金额数据有误！";
                    return ErrMsg;
                }

                var nsr = new BLL.DJ_NSRXX().GetList(1, string.Format("[NSRBM] = '{0}'", r["纳税人编码"]), "NSRBM").Tables[0];
                if (nsr.Rows.Count == 0)
                {
                    ErrMsg = "Excel文件第" + excelRowIndex + "行，该纳税人编码不存在！";
                    return ErrMsg;
                }
                else
                {

                    if (new BLL.TaxAuditForm().ExistsByYGZ(nsr.Rows[0]["NSRDZDAH"].ToString(), r["年度"].ToString()))
                    {
                        ErrMsg += r["纳税人名称"].ToString() + "已进行结算补贴；";
                        return ErrMsg;
                    }
                }

                var NSRDZDAH = decimal.Parse(nsr.Rows[0]["NSRDZDAH"].ToString());
                if (!isDel)
                {
                    if (_bll.Exists(year, NSRDZDAH, period))
                    {
                        ErrMsg = "Excel文件第" + excelRowIndex + "行，数据已存在，不能重复导入！";
                        return ErrMsg;
                    }
                }

                var model = new Model.YGZAllowance();
                model.FYear = year;
                model.FPeriod = period;
                model.FAmount = amount;
                model.NSRDZDAH = NSRDZDAH;
                model.FYGZAllowanceNo = DateTime.Now.ToString("yyyyMMddHHmmss") + i;
                model.FExcelFileName = svrFileName;
                model.FExcelRowNumber = excelRowIndex;
                model.FEntityNo = GlobalConstant.ENTITYNO;
                model.FInsDate = DateTime.Now;
                model.FInsDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                model.FInsEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                model.FInsIP = GenerateUtil.GetClientIPv4Address();
                model.FUpdDate = model.FInsDate;
                model.FUpdDeptNo = model.FInsDeptNo;
                model.FUpdEmplNo = model.FUpdEmplNo;
                model.FUpdIP = model.FInsIP;
                models.Add(model);
            }

            //保存
            if (isDel)
            {
                _bll.DeleteModels(year, period);
            }
           
            var isSuccess = _bll.AddList(models);
            if (ErrMsg != "")
            {
                return isSuccess ? "导入成功！其中以下数据存在异常：" + ErrMsg : ErrMsg;
            }
            return isSuccess ? "ok" : ErrMsg;

        }

        //取纳税人名称
        public string GetNSRMC(string id)
        {
            var NSRMC = "";
            var nsr = new BLL.DJ_NSRXX().GetList(1, string.Format("[NSRBM] = '{0}'", id), "NSRBM").Tables[0];
            if (nsr.Rows.Count != 0)
            {
                NSRMC = string.Format("{0}|{1}",nsr.Rows[0]["NSRMC"],nsr.Rows[0]["NSRDZDAH"]);
            }
            return NSRMC;
        }

        #region 纳税人名称自动匹配列表

        public ActionResult LargeDataComboBoxPartial()
        {
            return PartialView();
        }

        public static object GetNsrRange(ListEditItemsRequestedByFilterConditionEventArgs args)
        {
            var skip = args.BeginIndex;
            var take = args.EndIndex - args.BeginIndex + 1;
            var nsrmc = args.Filter;

            if (!string.IsNullOrEmpty(nsrmc))
            {
                var nsrxxBll = new BLL.DJ_NSRXX();
                var nsrs = nsrxxBll.DataTableToList(nsrxxBll.GetList(100, string.Format("NSRMC LIKE '%{0}%'", nsrmc), "NSRMC").Tables[0]);
                return (from nsr in nsrs
                        select nsr
                        ).Skip(skip).Take(take);
            }
            return null;
        }

        public static object GetNsrByID(ListEditItemRequestedByValueEventArgs args)
        {
            if (args.Value != null)
            {
                var id = args.Value.ToString();
                var year = OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
                var nsrxxBll = new BLL.DJ_NSRXX();
                var nsrs = nsrxxBll.GetModelList(string.Format("NSRBM like '%{0}%'",id));
                if (nsrs.Count > 0)
                {
                    return nsrs[0];
                }
            }
            return null;
        }

        #endregion

        //模板下载
        public ActionResult ExcelTemplateFileDownload(string id)
        {           
            var filePath = Server.MapPath("~/DataTemplate/" + id);
            var result = new Common.FileResult() { FilePaht = filePath, FileName = id };            
            return result;
        }


    }
}
